<?php
namespace app\api\model;
use think\Model;
use think\facade\Db; // 关键：引入Db门面
class Category extends Model
{
    protected $pk = 'id';
    // 商品类别列表
    public static function getCategoryList($page=1,$pageSize=10,$keyword='')
    {
        $query = new self();

        if (!empty($keyword)) {
            $query=$query->where(function ($q) use ($keyword) {
                $q->where('category_name', 'like', "%{$keyword}%");
            });
        }
        $list = $query->order('create_time','desc')
                      ->paginate([
                        'list_rows' => $pageSize,
                        'page' => $page
                    ]);
        $data = $list;
        return ['code'=>200,'msg'=>'success','data'=>$data];
    }
 
    // 添加商品类别
    public static function addCategory($data)
    {
        $category = new self();
        $category->category_name = $data['category_name'];
        $category->save();
        return ['code'=>200,'msg'=>'success'];
    }
    // 修改商品类别
    public static function editCategory($data)
    {
        $category = self::where('id', $data['id'])->find();
        if (empty($category)) {
            return ['code'=>400,'msg'=>'商品类别不存在'];
        }
        $category->category_name = $data['category_name'];
        $category->save();
        return ['code'=>200,'msg'=>'success'];
    }
    // 删除商品类别
    public static function deleteCategory($id)
    {
        $category = self::where('id', $id)->find();
        if (empty($category)) {
            return ['code'=>400,'msg'=>'商品类别不存在'];
        }
        $category->delete();
        return ['code'=>200,'msg'=>'success'];
    }
}